using System;
using OFX.Aggregator.WebScraping.Infrastructure;

namespace OFX.Aggregator.WebScraping.Implementation.BESnet.Checking.HtmlPageProcessing
{
	public class BESnetAccountHomePageProcessor : IHtmlPageProcessor
	{
		#region Implementation of IHtmlPageProcessor

		public void TestAssumptions(IHtmlDocument document)
		{
			try
			{
				if (document.Frames.Count != 3)
					throw new AssumptionFailedException(this,
					                                    string.Format("Expected 3 IFRAMEs in page, found {0}.",
					                                                  document.Frames.Count));

				IHtmlFrameWindow frame = document.Frames[1];

				IHtmlDocument innerDocument = frame.Document;
				IHtmlElement atalhos = innerDocument.GetElementById("tdAtalhos");
				if (atalhos == null || atalhos.TagName != "TD")
				{
					throw new AssumptionFailedException(this,
					                                    string.Format("Expected element with id {0} not found in page!", "tdAtalhos"));
				}

				IHtmlElement link = atalhos.Children[0];
				if (link == null || link.TagName != "A")
				{
					throw new AssumptionFailedException(this,
					                                    string.Format("Expected element not found in page!"));
				}

				if (link.GetAttribute("href") == null)
				{
					throw new AssumptionFailedException(this,
					                                    string.Format(
					                                    	"Element does not contain expected attribute @href!"));
				}

				if (string.IsNullOrEmpty(link.InnerText) || link.InnerText != "Saldo")
				{
					throw new AssumptionFailedException(this,
					                                    string.Format("Element does not contain known text!"));
				}
			}
			catch (InvalidCastException e)
			{
				throw new AssumptionFailedException(this, "Element found was of different type than expected!", e);
			}
		}

		public void ProcessPage(IHtmlDocument document, IHtmlPageProcessorFinished finished)
		{
			IHtmlElement link = getCreditCardStatementMenuLink(document);

			link.Click();
		}

		#endregion

		private static IHtmlElement getCreditCardStatementMenuLink(IHtmlDocument document)
		{
			IHtmlFrameWindow frame = document.Frames[1];

			IHtmlDocument innerDocument = frame.Document;
			IHtmlElement atalhos = innerDocument.GetElementById("tdAtalhos");
			IHtmlElement link = atalhos.Children[0];

			return link;
		}
	}
}